package tools

import (
	"encoding/json"
	"fmt"
	"time"

	"techoiceness.com/aiagent/llm-gateway/internal/llm/types"
)

// TimeTool 时间工具
type TimeTool struct {
}

// NewTimeTool 创建时间工具
func NewTimeTool() *TimeTool {
	return &TimeTool{}
}

func (t *TimeTool) Name() string {
	return "get_current_time"
}

func (t *TimeTool) Description() string {
	return "Get current date and time"
}

func (t *TimeTool) Definition() types.Tool {
	return types.Tool{
		Type: "function",
		ToolFunction: types.ToolFunction{
			Name:        t.Name(),
			Description: t.Description(),
			Parameters: types.JSONSchema{
				Type: "object",
				Properties: map[string]*types.JSONSchema{
					"format": {
						Type:        "string",
						Description: "Time format (default: RFC3339)",
					},
					"timezone": {
						Type:        "string",
						Description: "Timezone (default: UTC)",
					},
				},
			},
		},
	}
}

func (t *TimeTool) Execute(arguments string) (string, error) {
	var params struct {
		Format   string `json:"format"`
		Timezone string `json:"timezone"`
	}

	// 设置默认值
	params.Format = "RFC3339"
	params.Timezone = "UTC"

	if arguments != "" {
		if err := json.Unmarshal([]byte(arguments), &params); err != nil {
			return "", fmt.Errorf("invalid arguments: %w", err)
		}
	}

	now := time.Now()

	// 处理时区
	if params.Timezone != "UTC" {
		if loc, err := time.LoadLocation(params.Timezone); err == nil {
			now = now.In(loc)
		}
	}

	// 格式化时间
	var formatted string
	switch params.Format {
	case "RFC3339":
		formatted = now.Format(time.RFC3339)
	case "unix":
		formatted = fmt.Sprintf("%d", now.Unix())
	case "human":
		formatted = now.Format("2006-01-02 15:04:05")
	default:
		formatted = now.Format(params.Format)
	}

	result := map[string]interface{}{
		"current_time": formatted,
		"timezone":     params.Timezone,
		"format":       params.Format,
		"unix":         now.Unix(),
	}

	resultJSON, _ := json.Marshal(result)
	return string(resultJSON), nil
}
